<template>
  <div class="step-two" :style="{ fontSize: fontSize == 'large' ? '0.9vw' : (fontSize == 'medium' ? '0.8vw' : '0.7vw') }">
    <div class="ability-box">
      <div class="examinee-info">
        <div class="info-item">
          <div class="item-title">考场号</div>
          <div class="item-text">{{examAddress}}考台</div>
        </div>
        <div class="info-item pb10">
          <div class="item-title">考生信息</div>
          <div class="item-text">姓名</div>
          <div class="item-text">{{userInfo.nickname}}</div>
          <div class="item-text">性别</div>
          <div class="item-text">男</div>
        </div>
        <div class="info-item">
          <div class="item-title">科目</div>
          <div class="item-text">科目{{types==1?'一':'四'}}</div>
        </div>
        <div class="info-item">
          <div class="item-title">剩余时间</div>
          <div class="item-timer"
            :style="{ fontSize: fontSize == 'large' ? '1.3vw' : (fontSize == 'medium' ? '1.2vw' : '1.1vw') }">{{
              times || '44:59' }}</div>
        </div>
      </div>
      <div class="topic-info">
        <div class="topic-large-box">
          <div class="topic-stem">
            <div class="stem-title">考试题目</div>
            <div class="stem-body">
              <div class="stem">
                {{ page + '.' }}{{ currentTopic.title }}
              </div>
              <div class="stem-options" v-for="(item, index) in currentTopic.options" :key="index">
                {{ item.option }}、{{ item.content }}
              </div>
            </div>
            <div class="user-option"
              :style="{ fontSize: fontSize == 'large' ? '1.0vw' : (fontSize == 'medium' ? '0.9vw' : '0.8vw') }">
              <div>你选择的答案</div>
              <!-- 用户选项 -->
              <div class="user-op" v-if="currentTopic.key == ''">
                <div class="option-item" :class="item.isSelect ? 'is-select' : ''"
                  v-for="(item, index) in currentTopic.options" :key="index" @click="selected(item)">
                  {{ item.option }}
                </div>
              </div>
              <!-- 用户选项 选择 -->
              <div class="user-op" v-if="currentTopic.key != ''">
                <div class="option-item" :class="item.isSelect ? 'is-select' : ''"
                  v-for="(item, index) in currentTopic.options" :key="index">
                  {{ item.option }}
                </div>
              </div>
            </div>
          </div>
          <div class="topic-bank">
            <div class="bank-item" v-for="(item, index) in tableData" :key="index" @click="selectTopic(item, index)">
              <div>{{ index + 1 }}</div>
              <!-- 对错 -->
								<div :class="item.key == item.trueKey ? '': 'wrong-text'" v-if="item.key != ''">
									<!-- {{(item.key == item.trueKey?'√': 'X') || index+1}} -->
									{{(item.key == item.trueKey?item.key: item.key) }}
                </div>
								<!-- 用户没有选择 -->
								<div v-if="item.key == ''">
									<!-- {{item.key || index+1}} -->
                </div>
            </div>
          </div>
        </div>
        <div class="tool-box">
          <div class="tool-item" @click="chengeTopic(1)" :disabled="upper">上一题</div>
          <div class="tool-item" @click="chengeTopic(2)" :disabled="downer">下一题</div>
          <div class="tool-item" @click="playVoice">读题</div>
          <div class="tool-submit" @click="tipsShow = true">交卷</div>
        </div>
      </div>
    </div>
    <div class="topic-analysis">
      <div class="topic-tool-case">
        <div>本题为判断题，请选择你认为正确的答案！</div>
        <div class="case-option" @click="OnAutoNext">
          <img :src="autoNext ? require('@/assets/right.png') : require('@/assets/select.png')" alt="" />
          <div>答对自动下一题</div>
        </div>
        <div class="case-option" @click="OnErrShowSkill">
          <img :src="errShowSkill ? require('@/assets/right.png') : require('@/assets/select.png')" alt="" />
          <div>答错显示技巧</div>
        </div>
        <div class="case-option" @click="OnIsVoice">
          <img :src="isVoice ? require('@/assets/right.png') : require('@/assets/select.png')" alt="" />
          <div>开启语音</div>
        </div>
        <div class="case-option">
          <div>字体大小</div>
          <div class="case-options" @click="OnFontSize('large')">
            <img :src="fontSize == 'large' ? require('@/assets/right.png') : require('@/assets/select.png')" alt="" />
            <div>大</div>
          </div>
          <div class="case-options" @click="OnFontSize('medium')">
            <img :src="fontSize == 'medium' ? require('@/assets/right.png') : require('@/assets/select.png')" alt="" />
            <div>中</div>
          </div>
          <div class="case-options" @click="OnFontSize('small')">
            <img :src="fontSize == 'small' ? require('@/assets/right.png') : require('@/assets/select.png')" alt="" />
            <div>小</div>
          </div>
        </div>
      </div>
      <div class="analysis-box">
        <div class="analysis-info f2">
          <div class="analysis-title"
            :style="{ fontSize: fontSize == 'large' ? '1.0vw' : (fontSize == 'medium' ? '0.9vw' : '0.8vw') }">
            图片信息</div>
          <div class="analysis-img">
            <img :src="currentTopic.full_image" alt="" />
          </div>
        </div>
        <div class="analysis-info f1" v-show="errShowSkill && isSelect">
          <div class="analysis-title"
            :style="{ fontSize: fontSize == 'large' ? '1.0vw' : (fontSize == 'medium' ? '0.9vw' : '0.8vw') }">
            技巧讲解</div>
          <div class="analysis-txt">
            {{currentTopic.official_parse}}
          </div>
        </div>
      </div>
    </div>
    <div class="popups-box" v-if="tipsShow">
      <div class="popups-body">
        <div class="tips-text">
          点击【确认交卷】，将提交考试成绩，结束考试！<br />
          点击【继续考试】，将关闭本次窗口，继续考试！
        </div>
        <div class="btn-box">
          <div class="green" @click="tipsShow = false">继续考试</div>
          <div @click="handlePapers()">确认交卷</div>
        </div>
        <img class="exit-btn" src="@/assets/EXIT.png" alt="" @click="tipsShow = false" />
      </div>
    </div>
  </div>
</template>

<script>
import {
  getExams,
  submitExamInfo
} from '@/api/index.js';
export default {
  props:['examAddress','types'],
  data() {
    return {
      tipsShow: false,
      // 考试时间
      times: null,
      // 考试结束时间
      endTime: null,
      // 答对数
      trueNum: 0,
      // 答错数
      wrongNum: 0,
      // 没做数
      notDoNum: 0,
      // 答对自动下一题
      autoNext: false,
      // 答错显示技巧
      errShowSkill: false,
      // 用户是否选择
      isSelect: false,
      // 开启语音
      isVoice: false,
      // 字体大小
      fontSize: 'medium',
      // 上一题 下一题 按钮控制器
      upper: false,
      downer: false,
      // 语音
      Audio: new SpeechSynthesisUtterance(),
      synth: window.speechSynthesis,// 启用文本
      // 当前题目消息
      currentTopic: {},
      currentTopicIndex: 0,
      // 题目数据集合
      tableData: [],
      // 用户答题信息，用于提交考试
      answerInfo: [],
      // 当前用户信息
      userInfo:{},
      page: 1,
      limit: 1,
      //  1、科目一 2、科目四
      currentTag: 1
    };
  },
  mounted() {
    this.init()
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
    // console.log(11,this.userInfo)
  },
  methods: {
    handlePapers() {
      this.computeSelect()
      this.$emit('getSteps', 1)
    },
    init() {
      this.getTime();
      let that = this
      getExams({
        subject: this.types,
      }).then(res => {
        let arr = res.data;
        if (that.types == 1) {
          arr.map(item => {
            item["isSelect"] = false
            item["key"] = ''
            item["trueKey"] = item.correct_options[0].option
            if (item.type == 3) {
              for (const iter of item.options) {
                if (iter.option == 'A') {
                  // console.log(88)
                  iter.option = '√'
                }
                if (iter.option == 'B') {
                  iter.option = 'X'
                }
              }
            }
          })
        }
        that.tableData = arr;
        that.currentTopic = this.tableData[0];
        that.page = 1
        // console.log(89999999999,that.tableData);
      }).catch()
    },
    // 答对自动下一题
    OnAutoNext() {
      this.autoNext = !this.autoNext
    },
    // 答错显示技巧
    OnErrShowSkill() {
      this.errShowSkill = !this.errShowSkill
    },
    // 开启语音
    OnIsVoice() {
      this.isVoice = !this.isVoice
    },
    // 字体大小
    OnFontSize(str) {
      if (this.fontSize != str) {
        this.fontSize = str
      }
    },
    // 提交考试
			submitExamInfos() {
				// console.log(this.tableData);
				// 计算花费多少时间
				let t1 = this.times.split(':');
				let t2 = 44 - parseInt(t1[0]);
				let t3 = 59 - parseInt(t1[1])
				let obj = {
					subject: parseInt(this.types),
					room_number: this.examAddress,
					name_candidate: this.userInfo.nickname,
					candidate_gender: (this.userInfo.sex || 3),
					take_seconds: (t2 * 60 + t3),
					questions: this.answerInfo
				}

				let that = this
				submitExamInfo(obj).then(res => {
					setTimeout(() => {
						that.$emit('getSteps', 3, res.data);
						// that.$emit('getExamTotal',res)
						// that.getExamTotal(res)
					}, 500)
					// console.log(111111,res);
				}).catch()
			},
    // 单选、判断
    // 多选
    
    // 语音播报
    playVoice() {
      if (!this.isVoice) {
        this.$message({
          message: '没有开启语音功能',
          type: 'warning'
        });
        return;
      }
      // let u = new SpeechSynthesisUtterance();
      let str = this.currentTopic.title
      this.synth.cancel(str)
      this.Audio.text = str;
      this.Audio.lang = 'zh';
      //u.rate = 0.7
      speechSynthesis.speak(this.Audio);
    },

    // 判断按钮可否可点击 上一题  下一题
    isCanClick(type) {
      this.isSelect = false
      // 上 且 在第一个题时
      if (type == 1 && this.currentTopicIndex == 0) {
        this.upper = true
        this.$message({
          message: '已经是第一题了',
          type: 'warning'
        });
      }
      if (type == 1 && this.currentTopicIndex != 0) {
        this.upper = false
        this.downer = false
        this.currentTopicIndex = this.currentTopicIndex - 1
        this.page -= 1
      }

      if (type == 2 && this.currentTopicIndex == 99) {
        this.downer = true
        this.$confirm('已经是最后一题了,是否交卷?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      }
      if (type == 2 && this.currentTopicIndex != 99) {
        this.downer = false
        this.upper = false
        this.currentTopicIndex = this.currentTopicIndex + 1
        this.page += 1
      }
    },
    // 切换题目
    chengeTopic(type) {
      this.isCanClick(type)
      this.tableData.forEach(ele => {
        ele.ischecked = false
      })
      this.currentTopic = this.tableData[this.currentTopicIndex]
      this.tableData[this.currentTopicIndex].ischecked = true
      this.page = this.currentTopicIndex + 1
      this.isSelect = false
    },
    // 点击选择题目
    selectTopic(item, index) {
      this.page = index + 1
      this.currentTopic = item
      this.currentTopicIndex = index
      this.tableData.forEach(ele => {
        ele.ischecked = false
      })
      item.ischecked = true
      this.isSelect = false
    },
    // 计算用户选择信息
			computeSelect() {
				// 其中is_correct(是否正确 1是 0否)不传默认为0，is_answer(是否答题 1是 0否),不传默认为0
				// key用户选择   trueKey正确答案
				for (let s of this.tableData) {
					// 查找用户答题选择对象
					let result = s.options.find(item => {
						return item.option == s.key
					})
					let correct1 = 0;
					let answer = 0;
					// 用户答对
					if (s.key == s.trueKey) {
						correct1 = 1;
						answer = 1;
					}
					// 用户答错
					if (s.key != s.trueKey && s.key != '') {
						correct1 = 0;
						answer = 1;
					}
					// 用户未答
					if (s.key == '') {
						correct1 = 0;
						answer = 0
					}
					let o = {
						question_id: s.id,
						user_option_id: result == undefined ? 0 : result.id,
						is_correct: correct1,
						is_answer: answer
					}
					// 添加到考试信息中
					this.answerInfo.push(o)
				}
				this.submitExamInfos()
			},
    // 倒计时
    countDown(time) {
      var nowTime = +new Date(); //获取当前总毫秒数
      var inputTime = +new Date(time); //用户输入的总毫秒数
      var times = (inputTime - nowTime) / 1000; //剩余的总秒数
      //转换为分
      var m = parseInt(times / 60 % 60);
      m = m < 10 ? "0" + m : m
      //转换成秒
      var s = parseInt(times % 60);
      s = s < 10 ? "0" + s : s
      return m + ":" + s;
    },
    filterTime(time) {
      const date = new Date(time)
      const Y = date.getFullYear()
      const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      const D = date.getDate()
      const H = date.getHours() // 小时
      const m = date.getMinutes() // 分钟
      const S = date.getSeconds() // 秒
      return `${Y}-${M}-${D} ${H}:${m}:${S}`
      // return `${H}:${m}:${S}`
    },
    getTime() {
      this.endTime = new Date();
      let min = this.endTime.getMinutes();
      this.endTime = this.endTime.setMinutes(min + 45);
      this.endTime = this.filterTime(this.endTime)
      // return
      setInterval(() => {
        // console.log(this.endTime);
        this.times = this.countDown(this.endTime)
        if (this.times < 0) {
          clearInterval(this.times)
          this.times = 0
          // 交卷
          this.handlePaper()
        }
      }, 1000)
    },
    // 选择答案
    selected(item) {
      // this.errShowSkill = false;
      // 渲染选择的答案按钮
      this.tableData[this.currentTopicIndex].key = item.option
      item.isSelect = true
      // 如果答对了就直接跳到下一题,并且判断是否勾选自动下一题
      if (this.currentTopic.trueKey == item.option && this.autoNext) {
        this.chengeTopic(2)
      } else {
        // 如果答错了 判断是否勾选
        if(this.currentTopic.trueKey != item.option){
          this.isSelect = true;
        }
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.pb10 {
  padding-bottom: 15vh;
}

.ability-box {
  width: 100%;
  margin-top: 5vh;
  display: flex;

  .examinee-info {
    margin-right: 1vw;
    flex: 1;
    display: flex;
    flex-direction: column;
    // align-content: center;
    border: 1px solid #e6e6e6;

    .info-item {
      >div {
        text-align: center;
        padding: 1.5vh 3vw;
      }

      .item-title {
        color: #2ac092;
        border-bottom: 1px solid #e6e6e6;
        border-top: 1px solid #e6e6e6;
      }

      .item-timer {
        color: #ff6d6b;
        // font-size: 1.2vw;
      }
    }
  }

  .topic-info {
    flex: 6;

    .topic-large-box {
      display: flex;
      width: 100%;
      height: 80%;

      .topic-stem {
        // height: 100%;
        border: 1px solid #e6e6e6;
        margin-right: 1vw;
        flex: 1;
        position: relative;

        .stem-title {
          padding: 1.5vh 1vw;
          border-bottom: 1px solid #e6e6e6;
          color: #2ac092;
        }

        .stem-body {
          padding: 1vh 1vw;

          .stem {
            line-height: 2;
          }

          .stem-options {
            margin-bottom: 1vh;
          }
        }

        .user-option {
          position: absolute;
          bottom: 2vh;
          left: 2%;
          display: flex;
          justify-content: space-between;
          align-content: center;
          width: 96%;
          // font-size: 0.9vw;

          >div:nth-child(1) {
            display: flex;
            align-items: center;
          }

          .user-op {
            display: flex;

            >div {
              padding: 1.2vh 0.8vw;
              background-color: #f5f5f5;
              margin-left: 1vw;
              cursor: pointer;
            }
          }
        }
      }

      .topic-bank {
        flex: 1;
        // border: 1px solid #e6e6e6;
        display: flex;
        flex-wrap: wrap;

        .bank-item {
          width: 9.66%;
          display: flex;
          align-items: center;
          flex-direction: column;
          justify-content: center;
          cursor: pointer;
          user-select: none;
          border: 1px solid #e6e6e6;
        }
      }
    }

    .tool-box {
      display: flex;
      height: 20%;
      align-items: center;

      .tool-item,
      .tool-submit {
        padding: 1vh 1.8vw;
        border: 1px solid #e6e6e6;
        border-radius: 25px;
        width: 3vw;
        text-align: center;
        margin-right: 1vw;
        cursor: pointer;
      }

      .tool-item:hover {
        border: 1px solid #2ac092;
        color: #2ac092;
      }

      .tool-submit:hover {
        background: linear-gradient(180deg, #66ccad, #2ac092);
        color: #fff;
        border: none;
      }
    }
  }
}

.topic-analysis {
  margin-top: 2vh;
  border: 1px solid #e6e6e6;

  .topic-tool-case {
    display: flex;
    padding: 1vh 1vw;
    align-items: center;
    border-bottom: 1px solid #e6e6e6;

    img {
      width: 1vw;
      height: 2vh;
      margin-right: 0.5vw;
    }

    .case-option {
      display: flex;
      align-items: center;
      cursor: pointer;
      margin-left: 3vw;
    }

    .case-options {
      display: flex;
      align-items: center;
      cursor: pointer;
      margin-left: 1vw;
    }
  }

  .analysis-box {
    display: flex;

    .analysis-info {
      padding: 1vh 1vw;

      .analysis-title {
        // font-size: 0.9vw;
        font-weight: bold;
        margin-bottom: 2vh;
      }
    }

    .f1 {
      flex: 1;
      border-left: 1px solid #e6e6e6;
    }

    .f2 {
      flex: 2;
      margin-right: 2vw;
      border-right: 1px solid #e6e6e6;
    }
  }
}

.popups-box {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  bottom: 0;
  top: 0;
  right: 0;
  left: 0;
  z-index: 2086;
  background-color: rgba(127, 127, 127, 0.6);

  .popups-body {
    width: 20vw;
    height: 25vh;
    background-color: #fff;
    border-radius: 20px;
    position: relative;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .tips-text {
      flex: 3;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      align-items: center;
      color: #333333;
      font-size: 0.9vw;

      img {
        width: 2.2vw;
        height: 4.5vh;
      }

      .num {
        >span {
          font-size: 1.2vw;
          color: #2ac092;
        }
      }
    }

    .btn-box {
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: space-around;
      color: #666666;

      >div {
        cursor: pointer;
        height: 100%;
        border: 0.5px solid #e6e6e6;
        flex: 1;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .green {
        color: #2ac092;
      }
    }

    .exit-btn {
      position: absolute;
      cursor: pointer;
      top: 2vh;
      right: 1vw;
      width: 1.2vw;
      height: 2.5vh;
    }
  }
}

.is-select {
  color: #fff;
  background-color: #2AC092 !important;
}
.wrong-text {
		color: #FF6D6B;
	}
</style>